package me.tonywang.security.authentication;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @link UsernamePasswordAuthenticationFilter
 */
public class UserSignAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public static final String USER_SIGN_LOGIN_URL = "/user_sign";

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String userName = request.getParameter("username");
        String sign = request.getParameter("sign");
        userName = userName.trim();

        UserSignAuthenticationToken authRequest = new UserSignAuthenticationToken(
                userName, sign);

        // Allow subclasses to set the "details" property
        setDetails(request, authRequest);

        return this.getAuthenticationManager().authenticate(authRequest);
    }

    //如果验证时需要其他验证信息可以在此处扩展
    protected void setDetails(HttpServletRequest request,
                              UserSignAuthenticationToken authRequest) {
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public UserSignAuthenticationFilter() {
        super(new AntPathRequestMatcher(USER_SIGN_LOGIN_URL, "GET"));
    }

}
